
import cron from 'node-cron';
import { prisma } from '../service/mysql.js';
import { TaskStatus, TaskType } from '../plugins/schedule/type.js';
import { logger } from '../tools/index.js';
const taskMap = {};
const MIN_INTERVAL = 60 * 60 * 1000;
let wechatRobot = null;
// 初始化任务
export const initCronTask = async (robot) => {
    logger.info('initCronTask start....');
    wechatRobot = robot;
    const tasks = await prisma.t_schedule_task.findMany({
        where: {
            status: TaskStatus.VALID
        }
    });
    tasks.forEach(task => createTask(task.id, task.cron_expression, task.content));
}

// 创建调度任务
export const createTask = async (taskId, cronExpression, content) => {
    try {
        const task = cron.schedule(cronExpression, async () => {
            try {
                logger.info('do scheduleTask start, taskId = ', taskId);
                const scheduleTask = await prisma.t_schedule_task.findFirst({
                    where: {
                        id: taskId
                    }
                });
                if (scheduleTask.last_execution_time) {
                    const interval = new Date().getTime() - scheduleTask.last_execution_time.getTime();
                    if (interval < MIN_INTERVAL) {
                        logger.info('scheduleTask less min interval, taskId: ', taskId, ' interval = ', interval);
                        return;
                    }
                }
                
                // 执行任务
                const atWxUsers = await wechatRobot.getWxUsers([scheduleTask.create_account_no]);
                await wechatRobot.sendWxMessage(scheduleTask.book_id, `任务${scheduleTask.id}: ${scheduleTask.content}`, atWxUsers);

                  // 一次性任务执行后失效
                if (scheduleTask.task_type === TaskType.ONCE) {
                    await removeTask(scheduleTask.id);
                }

                // 更新最后执行时间
                await prisma.t_schedule_task.update({
                    where: {
                        id: taskId
                    },
                    data: {
                        last_execution_time: new Date()
                    }
                });
                logger.info('do scheduleTask successful, task = ', scheduleTask);
            } catch (err) {
                console.error('do scheduleTask error = ', err);
            }
        });
        taskMap[taskId] = task;
        logger.info('create cron task successful, taskId: ', taskId, ' cron expression: ', cronExpression, ' content = ', content);
    } catch (err) {
        console.error('create cron task error, taskId: ', taskId, ' err: ', err);
        await prisma.t_schedule_task.update({
            where: {
                id: taskId
            },
            data: {
                status: TaskStatus.INVALID
            }
        });
    }
}

// 创建调度任务
export const removeTask = async (taskId) => {
    const task = taskMap[taskId];
    if (task) {
        task.stop();
        taskMap[taskId] = null;
        await prisma.t_schedule_task.update({
            where: {
                id: taskId
            },
            data: {
                status: TaskStatus.INVALID
            }
        });
    }
}